package com.edu.dao;

import com.edu.bean.NewsComment;
import com.edu.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class NewsCommentDao {

    /**
     * 获取新闻评论列表（包含用户信息）
     */
    public List<Map<String, Object>> findCommentsByNewsId(Integer newsId) {
        List<Map<String, Object>> comments = new ArrayList<>();
        String sql = "SELECT c.*, u.username FROM news_comment c " +
                "LEFT JOIN user u ON c.user_id = u.user_id " +
                "WHERE c.news_id = ? AND c.status = 1 " +
                "ORDER BY c.create_time DESC";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, newsId);
            ResultSet rs = stmt.executeQuery();

            while (rs.next()) {
                Map<String, Object> comment = new HashMap<>();
                comment.put("commentId", rs.getInt("comment_id"));
                comment.put("newsId", rs.getInt("news_id"));
                comment.put("userId", rs.getInt("user_id"));
                comment.put("username", rs.getString("username"));
                comment.put("content", rs.getString("content"));
                comment.put("createTime", rs.getTimestamp("create_time"));
                comments.add(comment);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return comments;
    }

    /**
     * 删除评论
     */
    public boolean delete(Integer commentId) {
        String sql = "DELETE FROM news_comment WHERE comment_id = ?";

        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, commentId);
            return stmt.executeUpdate() > 0;

        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    /**
     * 添加评论
     */
    public boolean addComment(Integer newsId, Integer userId, String content) {
        String sql = "INSERT INTO news_comment (news_id, user_id, content, status, create_time) VALUES (?, ?, ?, 1, NOW())";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement stmt = conn.prepareStatement(sql)) {

            stmt.setInt(1, newsId);
            stmt.setInt(2, userId);
            stmt.setString(3, content);

            return stmt.executeUpdate() > 0;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return false;
    }
}